<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="登录"
      left-arrow
      @click-left="onBack"
    />
    <van-form ref="login-form" :show-error="false" :show-error-message="false" :validate-first="true" @submit="onLogin" @failed="onFailed">
      <van-field
        v-model="user.mobile"
        icon-prefix="toutiao"
        left-icon="shouji"
        placeholder="请输入手机号"
        name="mobile"
        center
        :rules="rule.mobile"
      />
      <van-field
        v-model="user.code"
        icon-prefix="toutiao"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        name="code"
        center
        :rules="rule.code"
      >
        <template #button>
          <van-count-down v-if="isCountDownShow" :time="1000 * 60" format="ss s" @finish="isCountDownShow = false"/>
          <van-button v-else class="send-btn" native-type="button" :loading="isSendSmsCodeLoading" loading-text="发送中" size="small" round @click.prevent="onSendCode">发送验证码</van-button>
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button type="info" block class="login-btn">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { login, sendSmsCode } from '@/api/user.js'
export default {
  name: 'LoginIndex',
  props: {},
  components: {
  },
  data () {
    return {
      user: {
        mobile: '13944444444',
        code: '246810'
      },
      rule: {
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '手机号格式错误' }
        ],
        code: [
          { required: true, message: '请输入验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式错误' }
        ]
      },
      isCountDownShow: false,
      isSendSmsCodeLoading: false
    }
  },
  computed: {},
  watch: {},
  methods: {
    ...mapMutations({
      setUser: 'user/setUser',
      removeCachePage: 'cache/removeCachePage'
    }),
    onBack () {
      this.$router.back()
    },
    async onLogin () {
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const { data } = await login(this.user)
        this.$toast.success('登录成功')
        // 默认写法
        // this.$store.commit('user/setUser', data.data)
        // 使用mapMutations
        this.setUser(data.data)
        this.removeCachePage('LayoutIndex')
        this.$router.back()
      } catch (e) {
        this.$toast.fail('登录失败，手机号或者验证码错误')
      }
    },
    onFailed (error) {
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: 'top'
        })
      }
    },
    async onSendCode () {
      // if (this.user.mobile === '') {
      //   this.$toast({ message: '请输入手机号', position: 'top' })
      // }
      // const regex = new RegExp(/^1[3|5|7|8|9]\d{9}$/, 'i')
      // if (!regex.test(this.user.mobile)) {
      //   this.$toast({ message: '手机号格式错误', position: 'top' })
      // }
      try {
        await this.$refs['login-form'].validate('mobile')
        this.isSendSmsCodeLoading = true
        await sendSmsCode(this.user.mobile)
        this.isCountDownShow = true
      } catch (err) {
        let message = ''
        if (err && err.response && err.response.status === 429) {
          message = '发送太频繁了，请稍后重试'
        } else if (err.name === 'mobile') {
          message = err.message
        } else {
          message = '未知错误'
        }
        this.$toast({ message: message, position: 'top' })
      }
      this.isSendSmsCodeLoading = false
    }
  },
  created () {
  },
  mounted () {
  },
  destroyed () {
  }
}
</script>

<style scoped lang='less'>
.login-container {
  .send-btn {
    width: 82px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      color: #666666;
      font-size: 11px;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      .van-button__text {
        color: 15px;
      }
    }
  }
}
</style>
